package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import org.hibernate.validator.constraints.URL;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Validated
public class UserController {

    private final UserService userService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        //判断用户名是否被抢占
        User u = userService.findByUserName(username);
        //判断信息格式是否合法
        if(u==null){
            //注册用户
            userService.register(username,Md5Util.getMD5String(password));
            return Result.success();
        }else {
            return Result.error("用户名已被使用");
        }

    }
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        //查询用户是否存在
        User loginUser = userService.findByUserName(username);
        if (loginUser==null){
            return Result.error("用户未注册");
        }
        //判断密码
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //登录成功
            //生成令牌jwt
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",loginUser.getId());
            map.put("username",loginUser.getUsername());
            String jwtToken = JwtUtil.genToken(map);
            return Result.success(jwtToken);
        }
        return  Result.error("登录失败，密码不对");
    }
    @GetMapping("/userInfo")
    public Result<User> queryUserInfo(HttpServletRequest request){
//        //从token中解析用户信息
//        String token = request.getHeader("Authorization");
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
//        Integer id = (Integer) map.get("id");
        //使用ThreadLocal
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        return Result.success(loginUser);

    }

    @PutMapping("/update")
    public Result<String> update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success("更新成功");

    }
    @PatchMapping("/updateAvatar")
    public Result<String> updateAvatar(@RequestParam @URL String imgUrl){
        userService.updateAvatar(imgUrl);
        return Result.success();

    }
    @PatchMapping("/updatePwd")
    public Result<String> updatePwd(@RequestBody Map<String,String> map){
        String old_pwd = map.get("old_pwd");
        String new_pwd = map.get("new_pwd");
        String re_pwd = map.get("re_pwd");
        if (!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd)||!StringUtils.hasLength(re_pwd)){
            return Result.error("缺少参数");
        }
        //对比旧密码是否输入正确
        Map<String,Object> map1 = ThreadLocalUtil.get();
        String username = (String) map1.get("username");
        User loginUser = userService.findByUserName(username);
        if (!(Md5Util.getMD5String(old_pwd).equals(loginUser.getPassword())) ){
            return  Result.error("原密码错误");
        }
        //应该在前端用js处理
        if (!new_pwd.equals(re_pwd)){
            return Result.error("新密码前后不一致");
        }
        userService.updatePwd(new_pwd,loginUser.getId());
        return Result.success();
    }
}
